/**
 *
 */
package wsepForum.network.server;

import java.util.Vector;

import wsepForum.network.common.GUIRequest;
import wsepForum.network.common.ITokenizer;
import wsepForum.network.common.RequestSerializer;
import wsepForum.network.common.GUIRequest.RequestType;

/**
* @author Oren Ben-Haim
*
*/
public class GUITokenizer<T> implements ITokenizer<GUIToken<T>> {

	/**
	 * char ASCII code of a backspace signal
	 */
	private final String FRAMING_CHAR = "\0";
	/**
	 * holds a buffer to typed chars
	 */
	private StringBuffer buffer;

	/*****************************
	 * CONSTRUCTOR               *
	 *****************************/
	public GUITokenizer() {
		this.buffer = new StringBuffer();
	}
	
	/*****************************
	 * MEMBERS                   *
	 *****************************/
	@Override
	public Vector<GUIToken<T>> process(String incoming) {
		this.buffer.append(incoming);
		String currentBuffer = this.buffer.toString()+" ";
		String[] splitted = currentBuffer.split(FRAMING_CHAR);

		if (splitted.length > 1) {
			Vector<GUIToken<T>> answer = new Vector<GUIToken<T>>(splitted.length-1);
			for (int i=0;i<splitted.length-1;i++) {
				answer.add(new GUIToken<T> (RequestSerializer.<T>deserialize(splitted[i])));
			}
			this.buffer.delete(0, this.buffer.length());
			this.buffer.append(splitted[splitted.length-1].substring(0, splitted[splitted.length-1].length()-1));
			return answer;
		}
		else {
			return null;
		}


	}





	// TODO Move to tests section
	public static void main(String[] args) {

			String coded = RequestSerializer.serialize(new GUIRequest(RequestType.CREATE_TOPIC,new Object[] {"moshe", 1, new Integer(3)},1));
			String coded2 = RequestSerializer.serialize(new GUIRequest(RequestType.ADD_MOD_TO_SECTION,new Object[] {"miko", 1, new Integer(3)},2));
			String coded3 = RequestSerializer.serialize(new GUIRequest(RequestType.EDIT_MESSAGE,new Object[] {"moshe", 1, new Integer(3)},3));
			String coded4 = RequestSerializer.serialize(new GUIRequest(RequestType.DELETE_MESSAGE,new Object[] {"moshe", 1, new Integer(3)},4));

			String data = coded +"\0"+ coded2+"\0"+ coded3+"\0"+coded4+"\0";
			String data1 = data.substring(0, 100);
			String data2 = data.substring(100);

			GUITokenizer<GUIRequest> tok = new GUITokenizer<GUIRequest>();
			Vector<GUIToken<GUIRequest>> vecvec = tok.process(data1);
			if (vecvec != null) {
			for (GUIToken<GUIRequest> serverToken : vecvec) {
				System.out.println(serverToken.getData().getRequestType());
			}}
			Vector<GUIToken<GUIRequest>> vecvec2 = tok.process(data2);
			for (GUIToken<GUIRequest> serverToken : vecvec2) {
				System.out.println(serverToken.getData().getRequestType());

				switch(serverToken.getData().getRequestType()) {
				case EDIT_MESSAGE:
					System.out.println("bla");
				}

			}

		}












}
